package com.webtest.common;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class DriverUtil {
    private static ChromeDriver driver;
    public static ChromeDriver getDriver() {
        if (driver == null) {
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("--remote-allow-origins=*");//解决 403 出错问题
            driver = new ChromeDriver(chromeOptions);
        }
        return driver;
    }
    // 生成一个动态的文件名称
    private static List<String> getName() {
        // 这里注意的是,同名的文件夹不会重复创建
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        String dirname = sim1.format(System.currentTimeMillis());
        SimpleDateFormat sim2 = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String filename = sim2.format(System.currentTimeMillis());
        List<String> list = new ArrayList<>();
        list.add(dirname);
        list.add(filename);
        return list;
    }
    /**  获取屏幕截图
     */
    public static void getScreenShot() throws IOException {
        File srcfile = driver.getScreenshotAs(OutputType.FILE);
        String destfile = "./src/test/" + getName().get(0) + "/" + getName().get(1) + ".png";
        FileUtils.copyFile(srcfile,new File(destfile));
    }
}
